package org.psyduck.config;

import org.apache.commons.lang3.StringUtils;
import org.psyduck.common.model.JsonBean;
import org.psyduck.common.model.JsonCode;
import org.psyduck.security.model.User;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.model.ApiInfo;
import org.ssssssss.script.MagicScriptContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class MagicApiSecurityConfig implements RequestInterceptor {

    @Override
    public Object preHandle(ApiInfo info, MagicScriptContext context, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String requireLogin = Objects.toString(info.getOptionValue("require_login"), "");
        if(requireLogin.equals("true") && String.valueOf(principal).equals("anonymousUser")){
            return new JsonBean(JsonCode.CERTIFICATE_EXPIRED);
        }
        String permission = Objects.toString(info.getOptionValue("permission"), "");
        try {
            if (StringUtils.isNotBlank(permission) && !((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).hasAuthority(permission)) {
                return new JsonBean(JsonCode.CERTIFICATE_EXPIRED);
            }
        } catch (Exception ignored) {
            if (StringUtils.isNotBlank(permission)) {
                return new JsonBean(JsonCode.NOT_FOUND_USER);
            }
        }
        return null;
    }

}
